/*
Library for DFRobot Flame Sensor
Product Code : RB-Dfr-65
Author: Jeff Szcinski II (jeffski)
*/

#include "Arduino.h"
#include "FlameSensor.h"

/**
constructor:
takes care of assigning pins for you 

@param analogInPin the input pin for the DFRobot
*/
FlameSensor::FlameSensor(int analogInPin){
	//turn debug statements off by default
	debug = false;
	
	sensorPin = analogInPin;
	sensorValue = -1;
	
	/*
	IMPORTANT NOTE: The value of the flameThreshold will change depending on the system.
	When the sensor is used independently with no other hardware in the arduino, the threshold level was extremely low: about 1 or 2.
	But once other components were running with the arduino the threshold went up to about 20-21. We are not sure why this is. 
	It could be noise from the other systems that are contributing to the naturally higher signal from the other components.
	*/
	flameThreshold = 15;
}

/**
returns true if a flame is detected, false otherwise
*/
bool FlameSensor::isFlame(){
	sensorValue = analogRead(sensorPin);
	
	if(debug){
		Serial.print("Flame Detection Level: ");
		Serial.println(sensorValue);
	}
	
	if(sensorValue > flameThreshold)
		return true;
	else
		return false;
}

/**
returns the average for a specified number of reads

@param readsNum the number of times the flame sensor should search for a flame
*/
int FlameSensor::getFlameDetectionAvg(int readsNum){
	//for those who just like to test how robust the code is
	if(readsNum == 0)
		return 0;
		
	int total = 0;
	
	for(int i = 0; i < readsNum; i++){
		sensorValue = analogRead(sensorPin);
		total += sensorValue;
		if(debug){
			Serial.print("Flame Detection Level: ");
			Serial.println(sensorValue);
		}
	}
	
	return total/readsNum;
}

/**
turns on debug statements
*/
void FlameSensor::setDebugOn(){
	debug = true;
}

/**
turns off debug statements
*/
void FlameSensor::setDebugOff(){
	debug = false;
}